package com.netty.demo.server.utils;


import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.util.Map;

/**
 * 动态java 类
 *
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年09月18日  17:29 </p>
 * <p>address: 四川成都 </p>
 */
public class DynamicClass {
    /**
     * 动态生成的类
     */
    private Object clazz = null;

    /**
     * 存放属性名称以及属性的类型
     */
    private BeanMap beanMap = null;

    public DynamicClass() {
        super();
    }

    public DynamicClass(Map<String, Class> propertyMap) {
        this.clazz = generateBean(propertyMap);
        this.beanMap = BeanMap.create(this.clazz);
    }

    public DynamicClass(Class superclass, Map<String, Class> propertyMap) {
        this.clazz = generateBean(superclass, propertyMap);
        this.beanMap = BeanMap.create(this.clazz);
    }

    private Object generateBean(Map<String, Class> propertyMap) {
        BeanGenerator generator = new BeanGenerator();
        BeanGenerator.addProperties(generator, propertyMap);
        return generator.create();
    }

    /**
     * 根据属性生成对象
     */
    private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
        BeanGenerator generator = new BeanGenerator();
        if (null != superclass) {
            generator.setSuperclass(superclass);
        }
        BeanGenerator.addProperties(generator, propertyMap);
        return generator.create();
    }

    /**
     * 给bean属性赋值
     *
     * @param property 属性名
     * @param value    值
     */
    public void setProperty(String property, Object value) {
        beanMap.put(property, value);
    }

    /**
     * 通过属性名得到属性值
     *
     * @param property 属性名
     * @return 值
     */
    public Object getProperty(String property) {
        return beanMap.get(property);
    }

    /**
     * 得到该实体bean对象
     *
     * @return bean对象
     */
    public Object getClazz() {
        return this.clazz;
    }
}
